package com.sk.cardeal.act.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.cardeal.R;
import com.sk.cardeal.adapter.ByPartsAdapter;
import com.sk.cardeal.adapter.ByPartsListAdapter;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.callback.CheckCallback;
import com.sk.cardeal.callback.HandleDataCallBack;
import com.sk.cardeal.entity.ByPartsKindList;
import com.sk.cardeal.entity.ByPartsList;
import com.sk.cardeal.entity.CheckEntity;
import com.sk.cardeal.utils.AppApi;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.utils.UIUtils;
import com.sk.cardeal.view.CustomPopWindow;
import com.sk.cardeal.view.FlowLayout;
import com.sk.cardeal.view.SimpleMultiStateView;
import com.sk.cardeal.view.TitleView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by sk on 2018/3/23.
 */

public class ChooseByPartsActivity extends BaseActivity implements HandleDataCallBack, BaseQuickAdapter.RequestLoadMoreListener, CheckCallback {
    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.ed_search)
    EditText edSearch;
    @BindView(R.id.down)
    ImageView down;
    @BindView(R.id.data_ryc)
    RecyclerView dataRyc;
    @BindView(R.id.SimpleMultiStateView)
    SimpleMultiStateView simpleMultiStateView;
    @BindView(R.id.view)
    View view;
    @BindView(R.id.brand_ryc)
    RecyclerView brandRyc;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.sure)
    TextView sure;
    private String result;
    private LoadingDialog loadingDialog;
    private List<ByPartsKindList.ResultListBean> kindlist = new ArrayList<>();
    private View popView;
    private FlowLayout popFlow;
    private List<ByPartsList.ResultListBean> allDataList = new ArrayList<>();
    private String searchString = "";
    private int page = 0;
    private String brandcode = "";
    private ByPartsListAdapter byPartsListAdapter;
    private boolean isLoadMore = false;
    private List<CheckBox> checkBoxList = new ArrayList<>();
    CustomPopWindow popWindow;
    private ByPartsAdapter topAdapter;
    private int count = 0;
    private ArrayList<ByPartsList.ResultListBean> selectList = new ArrayList<>();


    @Override
    protected int getContentView() {
        return R.layout.activity_choose_by_parts;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        titleView.setMyCallBack(this);

        EventBus.getDefault().register(this);

        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        result = getIntent().getStringExtra("data");

        popView = LayoutInflater.from(mContext).inflate(R.layout.layout_by_kind, null);
        popFlow = popView.findViewById(R.id.data_ryc);

        ByPartsKindList byPartsKindList = JSON.parseObject(result, ByPartsKindList.class);
        kindlist = byPartsKindList.getResultList();

        brandRyc.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        topAdapter = new ByPartsAdapter(R.layout.item_top_brand, kindlist);
        brandRyc.setAdapter(topAdapter);

        dataRyc.setLayoutManager(new LinearLayoutManager(mContext));
        byPartsListAdapter = new ByPartsListAdapter(R.layout.item_by_parts, allDataList, this);
        dataRyc.setAdapter(byPartsListAdapter);
        byPartsListAdapter.setOnLoadMoreListener(this, dataRyc);

        for (ByPartsKindList.ResultListBean data : kindlist) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_filter_check_box, popFlow, false);
            CheckBox checkBox = view.findViewById(R.id.original);
            checkBox.setText(data.getBrandName());
            checkBoxList.add(checkBox);
            popFlow.addView(view);
        }

        AppApi.getByPartsList(searchString, brandcode, page, this, 0, this);
        initSearch();

        for (int i = 0; i < checkBoxList.size(); i++) {
            final CheckBox checkBox = checkBoxList.get(i);
            final int finalI = i;
            checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (checkBox.isChecked()) {
                        EventBus.getDefault().post(new CheckEntity(finalI, true));
                    } else {
                        EventBus.getDefault().post(new CheckEntity(finalI, false));
                    }
                    popWindow.dissmiss();
                }
            });
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initSearch() {
        edSearch.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                    if (edSearch.getText().toString().length() > 0) {
                        searchString = edSearch.getText().toString();
                        loadingDialog.show();
                        page = 0;
                        allDataList.clear();
                        AppApi.getByPartsList(searchString, brandcode, page, ChooseByPartsActivity.this, 0, ChooseByPartsActivity.this);
                    } else {
                        Toast.makeText(mContext, "搜索关键字不能为空!", Toast.LENGTH_SHORT).show();
                    }
                }
                return false;
            }
        });
    }

    @Override
    public void clickTitle(int i) {
        super.clickTitle(i);
        switch (i) {
            case 1:
                finish();
                break;
        }
    }

    @OnClick({R.id.down, R.id.sure})
    public void onViewClicked(View view1) {
        switch (view1.getId()) {
            case R.id.down:
                popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                        .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                            @Override
                            public void onDismiss() {
                                view.setVisibility(View.GONE);
                            }
                        })
                        .setView(popView)//显示的布局，还可以通过设置一个View
                        .size(UIUtils.getScreenWidth(mContext), UIUtils.dip2px(mContext, 280))
                        .setFocusable(true)//是否获取焦点，默认为ture
                        .setOutsideTouchable(true)//0是否PopupWindow 以外触摸dissmiss
                        .create()//创建PopupWindow
                        .showAsDropDown(edSearch, 0, 0);//显示PopupWindow
                view.setVisibility(View.VISIBLE);
                break;
            case R.id.sure:
                Intent intent = new Intent();
                intent.putParcelableArrayListExtra("data", selectList);
                setResult(RESULT_OK, intent);
                finish();
                break;
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();

        ByPartsList byPartsList = JSON.parseObject(result, ByPartsList.class);
        List<ByPartsList.ResultListBean> dataBeanList = byPartsList.getResultList();
        if (page == 0) {
            allDataList.clear();
        }

        allDataList.addAll(dataBeanList);
        if (allDataList.size() < 10) {
            byPartsListAdapter.setEnableLoadMore(false);
        } else {
            byPartsListAdapter.setEnableLoadMore(true);
        }
        if (isLoadMore) {
            byPartsListAdapter.loadMoreComplete();
            if (dataBeanList.size() == 0) {
                byPartsListAdapter.loadMoreEnd();
            }
            isLoadMore = false;
        }
        byPartsListAdapter.notifyDataSetChanged();
    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();

    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();

    }

    @Override
    public void onLoadMoreRequested() {
        isLoadMore = true;
        page++;
        AppApi.getByPartsList(searchString, brandcode, page, ChooseByPartsActivity.this, 0, ChooseByPartsActivity.this);
    }

    @Override
    public void check(int pos, boolean check) {
        if (check) {
            allDataList.get(pos).setSelect(true);
            count++;
            addParts(pos);
        } else {
            allDataList.get(pos).setSelect(false);
            count--;
            reduceParts(pos);
        }
        tvTip.setText("已选择" + count + "件");
    }

    private void reduceParts(int pos) {

        boolean isContain = false;
        int p = 0;

        for (int i = 0; i < selectList.size(); i++) {

            if(allDataList.get(pos).getPartsId().equals(selectList.get(i).getPartsId())){
                isContain = true;
                p = i;
                break;
            }
        }
        if(isContain){
            selectList.remove(p);
        }
    }

    private void addParts(int pos) {
        selectList.add(allDataList.get(pos));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handlerEvent(CheckEntity checkEntity) {

        if (checkEntity.isCheck()) {
            for (int i = 0; i < kindlist.size(); i++) {
                if (i != checkEntity.getPos()) {
                    kindlist.get(i).setCheck(false);
                } else {
                    kindlist.get(i).setCheck(true);
                }
            }
            for (int i = 0; i < checkBoxList.size(); i++) {
                if (i != checkEntity.getPos()) {
                    checkBoxList.get(i).setChecked(false);
                } else {
                    checkBoxList.get(i).setChecked(true);
                }
            }
            loadingDialog.show();
            page = 0;
            brandcode = kindlist.get(checkEntity.getPos()).getBrandCode();
            AppApi.getByPartsList(searchString, brandcode, page, ChooseByPartsActivity.this, 0, ChooseByPartsActivity.this);

        } else {
            kindlist.get(checkEntity.getPos()).setCheck(false);
            checkBoxList.get(checkEntity.getPos()).setChecked(false);
            brandcode = "";
            AppApi.getByPartsList(searchString, brandcode, page, ChooseByPartsActivity.this, 0, ChooseByPartsActivity.this);
        }
        topAdapter.notifyDataSetChanged();
    }

}
